﻿using System;
using NHibernate;
using NaturalKeySpike.Common.DataAccess;

namespace NaturalKeySpike {
    public interface INhibernateUnitOfWork : IUnitOfWork {
        ISession CurrentSession { get; }
    }

    public class NhibernateUnitOfWork : INhibernateUnitOfWork {
        private readonly INhibernateSessionFactoryHelper _sessionFactoryHelper = new NhibernateSessionFactoryHelper();
        private ISession _session;

        public ISession CurrentSession {
            get { return _session ?? (_session = OpenSession()); }
        }

        public void Commit() {
            if (_session == null) return;

            _session.Transaction.Commit();
            _session.BeginTransaction();
        }

        public void Rollback() {
            if (_session == null) return;

            _session.Transaction.Rollback();
            _session.BeginTransaction();
        }

        public void Dispose() {
            if (_session == null) return;

            _session.Dispose();
            _session = null;
        }

        private ISession OpenSession() {
            var session = _sessionFactoryHelper.OpenSession();
            session.FlushMode = FlushMode.Commit;
            session.BeginTransaction();
            return session;
        }
    }
}
